package com.uyun.app.main.web;

import com.google.code.kaptcha.servlet.KaptchaExtend;
import com.uyun.app.main.service.MainService;
import com.uyun.util.AppUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class MainController extends KaptchaExtend {

    @Autowired
    private MainService mainService;

    private static final Logger logger = LoggerFactory.getLogger(MainController.class);


    @RequestMapping(value = "/")
    public String main() {

        Subject user = SecurityUtils.getSubject();

        if (user.isAuthenticated()) {
            return "index";
        } else {
            return "login";
        }

    }

    @RequestMapping(value = "/index")
    public String index() {

            return "index";

    }

    @RequestMapping(value = "/login")
    public String login() {

        Subject user = SecurityUtils.getSubject();

        if (user.isAuthenticated()) {
            return  "";
        } else {
            return "login";
        }
    }

    @RequestMapping(value = "/logon", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public @ResponseBody
    String logon(@RequestParam(required = true) String userId,
                 @RequestParam(required = true) String password,
                 @RequestParam(required = false) String captcha,
                 @RequestParam(required = true) String uuid,
                 HttpServletRequest request) {

        if (AppUtils.StringUtil(uuid) != null) {
            String kaptcha = (String) request.getSession().getAttribute(uuid);
            if (AppUtils.StringUtil(kaptcha) == null || !kaptcha.equals(captcha)) {
                return "5";
            }
        }

        try {
            password = AppUtils.md5Encode(AppUtils.md5Encode(password));
        } catch (Exception e) {
            logger.error("密码转换MD5失败！密码为：" + password, e);
        }

        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userId, password);

        try {
            user.login(token);
            token.setRememberMe(true);
            return "1";
        } catch (UnknownAccountException e1) {
            token.clear();
            return "2";
        } catch (LockedAccountException e2) {
            token.clear();
            return "3";
        } catch (Exception e) {
            token.clear();
            return "4";
        }

    }

    //@RequiresRoles("admin")
    @RequestMapping(value = "/signOut")
    public String signOut(HttpServletRequest request) {

        SecurityUtils.getSubject().logout();
        //以后都存到redis
        request.getSession().removeAttribute("currentUser");
        return  "login";


    }

    @RequestMapping(value = "/unauthorized")
    public String unauthorized() {


        return  "/error/404";


    }

    @RequestMapping(value = "/captcha")
    public void getCaptcha(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        String uuid = request.getParameter("uuid");
        super.captcha(request, response);
        String captcha = getGeneratedKey(request);
        //若分布式就放到redis或者memcached
        request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
        request.getSession().setAttribute(uuid, captcha);

    }


    @RequestMapping(value = "/404")
    public String error400() {
        System.out.println("custom error handler");
        return "/error/404";
    }

    @RequestMapping(value = "/hot")
    public String hot() {
        return "hot";
    }
    @RequestMapping(value = "/weather")
    public String weather() {
        return "weather";
    }
    @RequestMapping(value = "/news")
    public String news() {
        return "news";
    }


}